package org.rency.common.trigger.factory;

import javax.annotation.Resource;

import org.rency.common.trigger.schedule.DaemonContext;
import org.rency.common.trigger.service.ScheduleService;
import org.slf4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public abstract class AbstractDaemonJob implements DaemonJob {

	protected Logger logger = getLogger();
	
	private int batchSize = 50;
	
	@Resource(name="scheduleService")
	private ScheduleService scheduleService;
	
	@Resource(name="daemonTaskExecutor")
	private ThreadPoolTaskExecutor daemonTaskExecutor;
	 
	private String taskName;
	
	@Override
	public void execute(DaemonContext context) {
		this.setTaskName(context.getDescription());
		logger.info("开始执行任务 : [{}].",this.getTaskName());
		long star = System.currentTimeMillis();
		try{
			executeJob(context);
		}catch(Exception e){
			logger.error("任务[{}]执行异常,{}.",this.getTaskName(),e);
			exceptionHandle(context,e);
		}finally {
			long cost = System.currentTimeMillis() - star;
			logger.info("任务执行结束 : [{}], 耗时:[{}]毫秒.",this.getTaskName(),cost);
		}
	}
	
	private void exceptionHandle(DaemonContext context,Throwable e){
		scheduleService.triggerException(context.getTriggerId());
		exception(context,e);
	}	

	public int getBatchSize() {
		return batchSize;
	}
	
	public void setBatchSize(int batchSize) {
		this.batchSize = batchSize;
	}

	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public ThreadPoolTaskExecutor getDaemonTaskExecutor() {
		return daemonTaskExecutor;
	}
	
	public abstract void executeJob(DaemonContext context);
	
	public abstract void exception(DaemonContext context,Throwable e);
	
	public abstract Logger getLogger();
}
